import React, { useRef, useState } from 'react'
import { Form, Card, Row, Col, Typography, Button, Table, message } from 'antd';
import { reduce, isNil } from 'lodash';
import { withRouter, connect } from 'umi';

import { isSuccess } from '@/utils/request';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { personalIncomeTaxService } from '@/services/salaryManage/salaryCalculateService';

import BaseSettingProvider from '@/pages/SalaryManage/components/BaseSettingProvider';
import { NumberSettingInput } from '@/pages/SalaryManage/components/NumberSettingInput';
import { NumberSettingFormatter } from '@/pages/SalaryManage/components/NumberFormatter';
import {
    amountSettingColumn,
    percentSettingColumn
} from '@/pages/SalaryManage/utils/TableUtil'
import { TaxAmtSettingDescription } from '@/pages/SalaryManage/components/TaxAmtDescription';
import salaryManageStyle from '@/pages/SalaryManage/salaryManage.less';
import { pageTabProps } from '@/pages/SalaryManage/utils'
import { OrganizationNameHead } from '@/pages/SalaryManage/components/OrganizationName';
import pageStyles from './index.less';


const { Text } = Typography;
const { Item } = Form;

const formColProp = {
    wrapperCol: { span: 12 },
    labelCol: { span: 12 }
};

const colSpan = {
    md: 24,
    lg: 12,
    xl: 10
};

const buttonColSpan = {
    lg: 24,
    xl: 20
};

const columns = [
    {
        title: '级数',
        dataIndex: 'taxLevel',
        width: 80
    },
    {
        title: '累计预扣预缴应纳税所得额',
        dataIndex: 'taxAmt',
        width: 300,
        render(text, record) {
            return <TaxAmtSettingDescription record={record}/>
        }
    },
    percentSettingColumn({
        title: '预扣率%',
        dataIndex: 'taxRate'
    }),
    amountSettingColumn({
        title: '速算扣除数',
        dataIndex: 'quickDeductAmt'
    })
];

const calculateTax = async postValue => personalIncomeTaxService.calculate(postValue);

const TaxCalculator = React.forwardRef(({ form, location, organizationCode } /* , ref */) => {
    const { getFieldDecorator } = form;
    const numberProps = {
        maxLength: 16,
        thousandsSeparator: ','
    };

    const [show, setShow] = useState(false);
    const [calculateResult, setCalculateResult] = useState(false);
    const resultRef = useRef(null);
    const { taxRateId, name } = location.query;

    const reset = () => form.resetFields();
    const calculate = () => {
        form.validateFields(async (errors, values) => {
            if (errors) {
                return;
            }
            const fieldsValue = reduce(
                values,
                (result, value, key) => ({
                    ...result,
                    [key]: isNil(value) ? value : +String(value).replace(/,/g, '')
                }),
                {}
            );
            const postData = { taxRateId, ...fieldsValue };
            const result = await calculateTax(postData);

            if (!isSuccess(result)) {
                message.error(result.msg);
                return;
            }


            const resultData = result.data;
            setCalculateResult({
                ...resultData,
                dataSource: [{
                    taxLevel: resultData.taxLevel,
                    taxStartAmt: resultData.taxStartAmt,
                    taxEndAmt: resultData.taxEndAmt,
                    taxRate: resultData.taxRate,
                    quickDeductAmt: resultData.quickDeductAmt
                }]
            });
            setShow(true);

            if (resultRef.current) {
                // 让结果展示区域进入可见区域
                resultRef.current.scrollIntoView();
            }
        });
    };

    return (
        <PageHeaderWrapper type="success">
            <BaseSettingProvider organizationCode={organizationCode}>
                <Card
                    bordered={false}
                    title="个税计算器"
                    {...pageTabProps()}
                    extra={<OrganizationNameHead organizationCode={organizationCode} />}
                >
                    <div className={pageStyles.taxCalculator}>
                        <div className="header">
                            <Text type="secondary">个人所得税预扣率表：</Text>
                            <Text>{name}</Text>
                        </div>
                        <Form layout="horizontal" {...formColProp}>
                            <Row gutter={24}>
                                <Col {...colSpan}>
                                    <Item label="截止上月累计税前收入">
                                        {getFieldDecorator('totalAmt', {
                                            rules: [
                                                {
                                                    required: false,
                                                    message: '请输入截止上月累计税前收入'
                                                }
                                            ]
                                        })(<NumberSettingInput placeholder="请输入" {...numberProps} />)}
                                    </Item>
                                </Col>
                                <Col {...colSpan}>
                                    <Item label="本月税前收入">
                                        {getFieldDecorator('currentAmt', {
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '请输入税前收入'
                                                }
                                            ]
                                        })(<NumberSettingInput placeholder="请输入" {...numberProps} />)}
                                    </Item>
                                </Col>

                                <Col {...colSpan}>
                                    <Item label="截止上月累计医社保（个人）">
                                        {getFieldDecorator('totalSocial', {
                                            rules: [
                                                {
                                                    required: false,
                                                    message: '请输入截止上月累计医社保（个人）'
                                                }
                                            ]
                                        })(<NumberSettingInput placeholder="请输入" {...numberProps} />)}
                                    </Item>
                                </Col>
                                <Col {...colSpan}>
                                    <Item label="本月医社保（个人）">
                                        {getFieldDecorator('currentSocial', {
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '请输入本月医社保（个人）'
                                                }
                                            ]
                                        })(<NumberSettingInput placeholder="请输入" {...numberProps} />)}
                                    </Item>
                                </Col>

                                <Col {...colSpan}>
                                    <Item label="截止上月累计公积金（个人）">
                                        {getFieldDecorator('totalFund', {
                                            rules: [
                                                {
                                                    required: false,
                                                    message: '请输入截止上月累计公积金（个人）'
                                                }
                                            ]
                                        })(<NumberSettingInput placeholder="请输入" {...numberProps} />)}
                                    </Item>
                                </Col>
                                <Col {...colSpan}>
                                    <Item label="本月公积金（个人）">
                                        {getFieldDecorator('currentFund', {
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '请输入本月公积金（个人）'
                                                }
                                            ]
                                        })(<NumberSettingInput placeholder="请输入" {...numberProps} />)}
                                    </Item>
                                </Col>

                                <Col {...colSpan}>
                                    <Item label="截止上月累计税后加减项">
                                        {getFieldDecorator('totalItem', {
                                            rules: [
                                                {
                                                    required: false,
                                                    message: '请输入截止上月累计税后加减项'
                                                }
                                            ]
                                        })(
                                            <NumberSettingInput placeholder="请输入" {...numberProps} />
                                        )}
                                    </Item>
                                </Col>
                                <Col {...colSpan}>
                                    <Item label="本月税后加减项">
                                        {getFieldDecorator(
                                            'currentItem', {
                                                rules: [
                                                    {
                                                        required: false,
                                                        message: '请输入本月税后加减项'
                                                    }
                                                ]
                                            }
                                        )(<NumberSettingInput placeholder="请输入" {...numberProps} />)}
                                    </Item>
                                </Col>

                                <Col {...colSpan}>
                                    <Item label="截止上月累计免征额">
                                        {getFieldDecorator('totalExemption', {
                                            rules: [
                                                {
                                                    required: false,
                                                    message: '请输入截止上月累计免征额'
                                                }
                                            ]
                                        })(
                                            <NumberSettingInput placeholder="请输入" {...numberProps} />
                                        )}
                                    </Item>
                                </Col>
                                <Col {...colSpan}>
                                    <Item label="本月免征额">
                                        {getFieldDecorator('currentExemption', {
                                            initialValue: 5000.00,
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '请输入本月免征额'
                                                }
                                            ]
                                        })(<NumberSettingInput placeholder="请输入" {...numberProps} />)}
                                    </Item>
                                </Col>

                                <Col {...colSpan}>
                                    <Item label="截止上月累计专项扣款">
                                        {getFieldDecorator('totalSpecial', {
                                            rules: [
                                                {
                                                    required: false,
                                                    message: '请输入截止上月累计专项扣款'
                                                }
                                            ]
                                        })(
                                            <NumberSettingInput placeholder="请输入" {...numberProps} />
                                        )}
                                    </Item>
                                </Col>
                                <Col {...colSpan}>
                                    <Item label="本月专项扣款">
                                        {getFieldDecorator(
                                            'currentSpecial', {
                                                rules: [
                                                    {
                                                        required: false,
                                                        message: '请输入本月专项扣款'
                                                    }
                                                ]
                                            }
                                        )(<NumberSettingInput placeholder="请输入" {...numberProps} />)}
                                    </Item>
                                </Col>

                                <Col {...colSpan}>
                                    <Item label="截止上月累计已扣个税">
                                        {getFieldDecorator('totalTaxAmt', {
                                            rules: [
                                                {
                                                    required: false,
                                                    message: '请输入截止上月累计已扣个税'
                                                }
                                            ]
                                        })(
                                            <NumberSettingInput placeholder="请输入" {...numberProps} />
                                        )}
                                    </Item>
                                </Col>
                            </Row>

                            <Row className={pageStyles.buttonRow}>
                                <Col {...buttonColSpan} className={salaryManageStyle.textRight}>
                                    <Button onClick={reset}>重置</Button>
                                    <Button type="primary" onClick={calculate} className={salaryManageStyle.ml16}>
                                        计算
                                    </Button>
                                </Col>
                            </Row>

                            <div style={{ display: show ? 'block' : 'none' }} ref={resultRef}>
                                <div className="secondary">
                                    <div className="secondary-title">
                                        <Text className={salaryManageStyle.bold}>结果展示</Text>
                                    </div>
                                    <div className="secondary-wrapper">
                                        <Row gutter={24}>
                                            <Col {...colSpan}>
                                                <Col {...formColProp.labelCol} className={salaryManageStyle.textRight}>
                                                    <Text type="secondary">累计计税基数:</Text>
                                                </Col>
                                                <Col {...formColProp.wrapperCol} className={salaryManageStyle.bold}>
                                                    <NumberSettingFormatter value={calculateResult.totalBaseAmt} />
                                                </Col>
                                            </Col>
                                            <Col {...colSpan}>
                                                <Col {...formColProp.labelCol} className={salaryManageStyle.textRight}>
                                                    <Text type="secondary">累计应扣个税:</Text>
                                                </Col>
                                                <Col {...formColProp.wrapperCol} className={salaryManageStyle.bold}>
                                                    <NumberSettingFormatter value={calculateResult.totalTax} />
                                                </Col>
                                            </Col>
                                            <Col {...colSpan}>
                                                <Col {...formColProp.labelCol} className={salaryManageStyle.textRight}>
                                                    <Text type="secondary">累计已扣个税:</Text>
                                                </Col>
                                                <Col {...formColProp.wrapperCol} className={salaryManageStyle.bold}>
                                                    <NumberSettingFormatter value={calculateResult.totalIncomeTax} />
                                                </Col>
                                            </Col>
                                            <Col {...colSpan}>
                                                <Col {...formColProp.labelCol} className={salaryManageStyle.textRight}>
                                                    <Text type="secondary">本月应扣个税:</Text>
                                                </Col>
                                                <Col {...formColProp.wrapperCol} className={salaryManageStyle.bold}>
                                                    <NumberSettingFormatter value={calculateResult.currentTax} />
                                                </Col>
                                            </Col>
                                        </Row>
                                    </div>
                                </div>

                                <div className="table-wrapper">
                                    <div className="table-title">
                                        <Text className={salaryManageStyle.bold}>参考预扣率表级数</Text>
                                    </div>
                                    <Table
                                        rowKey="taxLevel"
                                        columns={columns}
                                        dataSource={calculateResult.dataSource}
                                        pagination={false}
                                        bordered
                                    />
                                </div>
                            </div>
                        </Form>
                    </div>
                </Card>
            </BaseSettingProvider>
        </PageHeaderWrapper>
    );
});

export default Form.create({})(connect((state, { location }) => ({
    organizationCode: location?.query?.organizationCode
}))(withRouter(TaxCalculator)));
